-- gain_fruit
-- Created by chengb Sep/11/2015
-- 成就：获得世界树果树

-- 内部函数声明
local whenDoItemBonus;

-- 注册获得物品的回调
EventMgr.register("game_achievement/gain_fruit", event.DO_BONUS, function(args)
    whenDoItemBonus(args);
end);

-- 注册获得物品的回调
whenDoItemBonus = function(bonus)
    if bonus[1] ~= 1 then
        -- 不是物品，不处理
        return;
    end
    
    local classId = bonus[2];
    local amount  = bonus[3];
    
    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == GameAchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end
        
        local config = GameAchievementM.query(id);
        local ruleArg = config["rule_arg"];
        if type(ruleArg["class_id"]) == 'number' and 
            ruleArg["class_id"] ~= classId then
            -- 不是需求的物品
            return false;
        end
        
        return true;
    end
    
    -- 遍历所有的子规则
    local ids = GameAchievementM.getIdsByRule("gain_fruit");
    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            GameAchievementM.tryComplete(id, amount);
        end
    end
end

return {
    -- 获取成就描述
    queryDesc = function(id)
        local config = GameAchievementM.query(id);

        local ruleArg  = config["rule_arg"];
        local progress = config["progress"];
        local desc     = config["desc"];
        
        desc = string.gsub(desc, "{0}", progress);

        return desc;
    end,
};